package com.cqeec.myblog.service;

import java.io.File;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import com.cqeec.myblog.dao.AlbumDao;
import com.cqeec.myblog.dao.AlbumDaoImpl;
import com.cqeec.myblog.model.Album;

public class AlbumServiceImpl implements AlbumService {
	private AlbumDao albumDao = new AlbumDaoImpl();

	@Override
	public Album saveAlbum(String bloggerId, String name, String description)
			throws ClassNotFoundException, SQLException {
		Album ablum = new Album();
		ablum.setId(UUID.randomUUID().toString().toUpperCase());
		ablum.setBlogger(bloggerId);
		ablum.setName(name);
		ablum.setCreationTime(new Date());
		ablum.setDescription(description);
		albumDao.save(ablum);
		return ablum;
	}

	@Override
	public List<Album> getAllAlbum(String albumPath) throws ClassNotFoundException, SQLException {
		List<Album> list = albumDao.findAll();
		// 设置相册封面照片
		File file;
		String[] photos;
		Random random = new Random();
		for (Album a : list) {
			if (a.getQuantity() > 0) {
				// 目录(data目录的绝对目录/博主的ID/相册的ID)
				file = new File(albumPath + "/" + a.getBlogger() + "/" + a.getId());
				photos = file.list();
				if (photos != null) {
					a.setCoverPhoto(a.getBlogger() + "/" + a.getId() + "/" + photos[random.nextInt(photos.length)]);
				}
			}
		}
		return list;
	}

	@Override
	public List<Album> getAllAlbum() throws ClassNotFoundException, SQLException {
		return albumDao.findAll();
	}

	@Override
	public void deleteAlbum(String id) throws ClassNotFoundException, SQLException {
		albumDao.delete(id);
	}

	@Override
	public void updateAlbum(String id, String name, String desc) throws ClassNotFoundException, SQLException {
		albumDao.update(id, name, desc);
	}

}
